var os = require('os');
var path = require('path');

var express = require('express');
var session = require('express-session');
var MongoStore = require('connect-mongostore')(session);

var favicon = require('static-favicon');
var logger = require('morgan');

var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compress = require('compression');

var flash = require('flash');
var log4js = require('log4js');

var csurf = require('csurf');
var reponseTime = require('response-time');
var busboy = require('connect-busboy');


var config = require('./config')


var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'jade');
app.set('view cache', !config.debug);

app.use(favicon('/public/favicon.ico'));

app.use(logger('dev'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cookieParser());
app.use(compress());

app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
    secret: 'session',
    key: 'sid',
    resave: true,
    store: new MongoStore({
        db: 'ulimob'
    }),
    saveUninitialized: true,
}));
app.use(flash()); // 消息中间件

// 日志
log4js.configure({
    appenders: [{
        type: 'console'
    }, {
        type: 'file',
        filename: 'logs/access.log',
        maxLogSize: 20480,
        backups: 4,
        category: 'Http://'
    }],
    replaceConsole: true
});

app.use(log4js.connectLogger(log4js.getLogger('Http://'), {
    level: 'auto',
    format: ':method :url'
}));

//logger.setLevel('INFO');
app.use(function(req, res, next) {
    req.logger = res.logger = function(name) {
        var logger = log4js.getLogger(name);
        return logger.setLevel('INFO');
    };
    next();
});


// 安全设定
app.use(csurf());
app.use(function(req, res, next) {
    res.locals.csrf = req.csrfToken ? req.csrfToken() : '';
    next();
});
app.use(reponseTime());
app.use(busboy({
    limits: {
        fileSize: 10 * 1024 * 1024 // 10MB
    }
}));


// 加载路由
app.use('/', require('./routes/home'));
app.use(require('./routes')(app));


/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


var cluster = require('cluster');

// 多核均衡负载
if (cluster.isMaster) {
    console.log("Master start...");

    // 绑定负载事件
    cluster.on('listening', function(worker, address) {
        console.log('Listening: worker ' + worker.process.pid + ', Address: ' + address.address + ":" + address.port);

    }).on('exit', function(worker, code, signal) {
        console.log('Worker ' + worker.process.pid + ': ' + worker.process.exitCode + ' died');
        console.log('Cluster %s fork', cluster.fork().process.pid);
    });

    // Fork workers.
    for (var i = 0; i < os.cpus().length; i++) {
        cluster.fork();
    }

} else {
    // 监听端口
    app.listen(8000);
}

module.exports = app;
